import React, { useState, useEffect, useRef } from "react";
import { Button, Input, message } from "antd";
import DynamicForm from "./view";
import type FieldSchema from "./type";
import { box } from "../../mobx/box";
import { observer } from "mobx-react-lite";

import "./index.scss";

const { TextArea } = Input;

const schemaTest: FieldSchema[] = [
  {
    type: "text",
    name: "Username",
    label: "用户名",
    attr: {
      rules: [{ required: true, message: "请输入用户名!" }],
      style: { border: "1px solid red" },
    },
    events: [
      {
        onClick: "console.log('Username:'+Username.text);",
        onKeyUp: "console.log('Username:'+Username.text);",
      },
    ],
  },
  {
    type: "password",
    name: "Password",
    label: "密码",
    attr: {
      rules: [{ required: true, message: "请输入密码!" }],
    },
    events: [
      {
        onClick: "console.log('Password:'+Password.text);",
        onKeyUp: "console.log('Password:'+Password.text);",
      },
    ],
  },
  {
    type: "select",
    name: "下拉框",
    label: "下拉框",
    options: ["A", "B"],
  },
  {
    type: "submit",
    name: "提交",
    attr: {
      type: "primary",
    },
    events: [
      {
        onClick:
          "console.log('Username:'+Username.text,'Password:'+Password.text);",
      },
    ],
  },
];
const RenderSchema = () => {
  const [schema, setSchema] = useState<FieldSchema[] | string>();
  const textAreaRef = useRef<any>(null);
  const childRef = useRef<any>();

  const parseSchema = async () => {
    let value = textAreaRef.current.resizableTextArea.textArea.value.trim();
    box.setLoading(true);
    await new Promise((resolve) => setTimeout(resolve, 1000));
    if (value[0] === "[") {
      setSchema(JSON.parse(value));
      box.setLoading(false);
      if (childRef.current.reset) {
        childRef.current.reset();
        message.success("解析成功");
      }
    } else {
      box.setLoading(false);
      message.error("解析失败,请输入正确格式的schema");
    }
  };

  useEffect(() => {}, []);

  return (
    <div id="page">
      <div className="left">
        <TextArea
          ref={textAreaRef}
          name="schemaInput"
          id="schemaInput"
          placeholder="请输入Schema..."
        ></TextArea>
        <Button id="parseSchema" size="large" onClick={parseSchema}>
          解析Schema
        </Button>
      </div>
      <div className="right">
        <DynamicForm
          ref={childRef}
          schema={schema as FieldSchema[]}
        ></DynamicForm>
      </div>
    </div>
  );
};

export default observer(RenderSchema);
